package com.xingdata.jjxc.activity;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import jar.MessageManager;
import jar.SimpleWebServer;
import jar.UDPServerSocket;
import jar.listener.ContentStateListener;
import jar.listener.InstructionListener;
import jar.model.HeartbeatEntity;
import jar.model.RequestEntity;
import jar.observer.CommunicationObserver;
import jar.tools.InstructionSet;
import jar.tools.UdpTools;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import org.json.JSONException;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.xingdata.jjxc.App;
import com.xingdata.jjxc.BuildConfig;
import com.xingdata.jjxc.ComEntity;
import com.xingdata.jjxc.Common;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.RequestCode;
import com.xingdata.jjxc.activity.viewdata.NaviViewData;
import com.xingdata.jjxc.ar_navi.ARHudComm;
import com.xingdata.jjxc.ar_navi.AR_Navi;
import com.xingdata.jjxc.ar_navi.DeviceConnectionEvent;
import com.xingdata.jjxc.ar_navi.LocationAdapter;
import com.xingdata.jjxc.ar_navi.NaviUpdateInfo;
import com.xingdata.jjxc.ar_navi.ProtoMsg;
import com.xingdata.jjxc.base.BaseTabActivity;
import com.xingdata.jjxc.callback.DilalogListener;
import com.xingdata.jjxc.callback.ViewCallback;
import com.xingdata.jjxc.enty.HudVersionEntity;
import com.xingdata.jjxc.enty.RespEntity;
import com.xingdata.jjxc.http.HttpResponseListener;
import com.xingdata.jjxc.http.HttpUtil;
import com.xingdata.jjxc.utils.ActivityTools;
import com.xingdata.jjxc.utils.JUtils;
import com.xingdata.jjxc.utils.SharedPreTools;
import com.xingdata.jjxc.utils.StringUtil;
import com.xingdata.jjxc.utils.SystemInfo;
import com.xingdata.jjxc.utils.ViewTools;
import com.xingdata.jjxc.utils.WeatherTools;
import com.xingdata.jjxc.views.MyAlertDialog;
import com.yepublib.zxsec.Jni;

/**
 * @Description: TODO(驾驾行车首页展示页面)
 * @date 2015-9-5 下午4:32:58 Creater JiangMin
 */
public class MainActivity extends BaseTabActivity implements OnClickListener, ViewCallback, InstructionListener,
		ContentStateListener {
	private String TAG = "MainActivity";
	/**
	 * 4 layout in FrameLayout with their id
	 */
	private Integer[] tabHost_layout_ids = { R.id.tabhost_navi };//, R.id.tabhost_carinfo, R.id.tabhost_my

	/** tag查找 */
	private String[] tab_titles;

	/**
	 * 4 button with their id name
	 */
	private Integer[] title_ids = { R.id.button_navi };//, R.id.button_carinfo, R.id.button_my
	
	private Integer[] layout_ids = { R.id.layout_navi };//, R.id.layout_carinfo,  R.id.layout_my

//	private MyViewData myViewData;
	private NaviViewData naviViewData;
//	private CarInfoViewData carinfodata;
	private Bundle savedInstanceState;
	private MessageManager manager;
//	private FindAllData findalldata;
	private Dialog exitDialog;
	private HashMap<String, String> weathMap;
	private static HudVersionEntity versionEntity;
	/** 3个方案布局 */
	public RelativeLayout routeRelative;
	LinearLayout layout;
    // 悬浮窗
	View float_window;
	public ImageView device_connectionIndicator;
	WindowManager windowManager;
	WindowManager.LayoutParams layoutParam = null;
	private float mTouchStartX;
	private float mTouchStartY;
	private float x;
	private float y;
	boolean initViewPlace = false;
    // 定位
    LocationAdapter locationAdapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
		App.instance.mainActivity = this;
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tabhost);
		this.savedInstanceState = savedInstanceState;
		routeRelative = (RelativeLayout)findViewById(R.id.mainRelative);
		layout = (LinearLayout)findViewById(R.id.layout_title);
		ActivityTools.addActivities(this);
		initView();
		initData();

		windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		LayoutInflater inflater = LayoutInflater.from(this);
		float_window = inflater.inflate(R.layout.ds3_device_connection_floatwindow,null);
		float_window.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						if (!initViewPlace) {
							initViewPlace = true;
							//获取初始位置
							mTouchStartX = event.getRawX();
							mTouchStartY = event.getRawY();
							x = event.getRawX();
							y = event.getRawY();
							Log.i(TAG, "startX:" + mTouchStartX + "=>startY:" + mTouchStartY);
						}else {
							//根据上次手指离开的位置与此次点击的位置进行初始位置微调
							mTouchStartX += (event.getRawX() -x);
							mTouchStartY += (event.getRawY() -y);
						}

						break;
					case MotionEvent.ACTION_MOVE:
						// 获取相对屏幕的坐标，以屏幕左上角为原点
						x = event.getRawX();
						y = event.getRawY();
						updateViewPosition();
						break;

					case MotionEvent.ACTION_UP:
						break;
				}
				return true;
			}
		});
		device_connectionIndicator = (ImageView) float_window.findViewById(R.id.device_float_indicator);
        layoutParam = new WindowManager.LayoutParams();
        addFloatWindow(float_window,layoutParam);

        // locationAdapter = LocationAdapter.InitInstance(this);
	}

	private void updateViewPosition() {
		// 更新浮动窗口位置参数
		layoutParam.x = (int) (x - mTouchStartX);
        layoutParam.y = (int) (y - mTouchStartY);
		windowManager.updateViewLayout(float_window, layoutParam);
	}

    Random random = new Random();
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void handleLocationChangeEvent(AMapLocation location){
		if(!App.deviceSettings.onBoardNavi){
			ARHudComm.getInstance().sendToAR(AR_Navi.sendDirection(location.getBearing(),location.getSpeed()));
		}
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void handleDeviceConnectionEvent(DeviceConnectionEvent event){
        if(event.id == DeviceConnectionEvent.Connected){
            device_connectionIndicator.setImageResource(R.drawable.device_connection_on);
        }
        if(event.id == DeviceConnectionEvent.Disconnected){
            device_connectionIndicator.setImageResource(R.drawable.device_connection_off);
        }
    }

	private void addFloatWindow(View layout,WindowManager.LayoutParams layoutParams){
		layoutParams.format = PixelFormat.TRANSLUCENT;
		layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
		layoutParams.x = 20;
		layoutParams.y = 300;
		layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
		layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
		layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
		windowManager.addView(layout,layoutParams);
	}

	@Override
	public void initData() {
		// naviViewData = new NaviViewData(tabContentView, MainActivity.this,
		// mHandler, savedInstanceState);
		naviViewData = new NaviViewData(tabContentView, MainActivity.this,
                mHandler, savedInstanceState,routeRelative,layout);
		try {
			weathMap = WeatherTools.getWeatherCode(MainActivity.this);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@SuppressWarnings("deprecation")
	@Override
	public void initView() {
		// 设置字体
		Typeface font = Typeface.createFromAsset(getAssets(), JUtils.TypefacePath);
//		((TextView) findViewById(R.id.title_find)).setTypeface(font);
//		((TextView) findViewById(R.id.title)).setTypeface(font);

		mTabHost = this.getTabHost();
		tab_titles = getResources().getStringArray(R.array.tabhost_titles);
		tabContentView = mTabHost.getTabContentView();
		
		for (int i = 0; i < tab_titles.length; i++) {
			TabSpec tabSpec = mTabHost.newTabSpec(tab_titles[i]).setIndicator(tab_titles[i])
					.setContent(tabHost_layout_ids[i].intValue());
			mTabHost.addTab(tabSpec);
		}
		
//		for (int i = 0; i < title_ids.length; i++) {
//			findViewById(title_ids[i]).setOnClickListener(this);
//		}
		
		for (int i = 0; i < layout_ids.length; i++) {
			findViewById(layout_ids[i]).setOnClickListener(this);
		}

		// 初始化发现界面
		mTabHost.setCurrentTabByTag(tab_titles[0]);
//		if (findalldata == null) {
//			findalldata = new FindAllData(tabContentView, MainActivity.this, savedInstanceState);
//		}

		manager = new MessageManager(SystemInfo.getServerPORT(), SystemInfo.getReceivePORT(), SystemInfo.timeOut, this,
				this, this);
		// 初始化视图工具类
		ViewTools.initScreen(this);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {

		case R.id.layout_navi:
			mTabHost.setCurrentTabByTag(tab_titles[0]);

			if (naviViewData == null) {
				naviViewData = new NaviViewData(tabContentView, MainActivity.this, mHandler, savedInstanceState,routeRelative,layout);
			}
			break;

//		case R.id.layout_carinfo:
//			mTabHost.setCurrentTabByTag(tab_titles[1]);
//			if (carinfodata == null) {
//				Log.d(TAG, "1");
//				carinfodata = new CarInfoViewData(tabContentView, MainActivity.this, mHandler);
//			}
//			break;

//		case R.id.layout_find:
//			mTabHost.setCurrentTabByTag(tab_titles[2]);
//			if (findalldata == null) {
//				findalldata = new FindAllData(tabContentView, MainActivity.this, savedInstanceState);
//			}
//			break;

//		case R.id.layout_my:
//			mTabHost.setCurrentTabByTag(tab_titles[3]);
//			if (myViewData == null) {
//				myViewData = new MyViewData(tabContentView, MainActivity.this, mHandler);
//			}
//			break;

		default:
			break;
		}
		setBackgroundDrawableResource(view.getTag());
	}

	// 设置背景颜色
	private void setBackgroundDrawableResource(Object tag) {
		int inTag = Integer.parseInt(tag.toString());

		for (int i = 0; i < title_ids.length; i++) {
			ImageView button = (ImageView) findViewById(title_ids[i]);
			switch (i) {

			case 0: 
				if (inTag != i) {
//					button.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_navi_normal));
					button.setBackgroundResource(R.drawable.tab_navi_normal);
				} else {
//					button.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_navi));
					button.setBackgroundResource(R.drawable.tab_navi);
				}

				break;
//			case 1:
//				if (inTag != i) {
//					button.setBackgroundResource(R.drawable.tab_carinfo_normal);
//				} else {
//					button.setBackgroundResource(R.drawable.tab_carinfo);
//				}
//
//				break;
//			case 2:
//				if (inTag != i) {
//					button.setBackgroundResource(R.drawable.tab_find_normal);
//				} else {
//					button.setBackgroundResource(R.drawable.tab_find);
//				}
//				break;
//			case 3:
//				if (inTag != i) {
//
//					button.setBackgroundResource(R.drawable.tab_my_normol);
//				} else {
//					button.setBackgroundResource(R.drawable.tab_my);
//				}
//
//				break;

			default:
				break;
			}

		}
		for (int i = 0; i < layout.getChildCount(); i++) {
			LinearLayout childLayout = (LinearLayout) layout.getChildAt(i);
			for (int j = 0; j < childLayout.getChildCount(); j++) {
				View view = childLayout.getChildAt(j);
				if (view instanceof Button) {

				} else if (view instanceof TextView) {
					if (i == inTag) {
						((TextView) view).setTextColor(getResources().getColor(R.color.blue3d_color));
					} else {
						((TextView) view).setTextColor(getResources().getColor(R.color.grey8_color));
					}

				}
			}
		}

	}

	@Override
	public void showToast(String mes) {
		showToast(mes);
	}

	@Override
	public void showProgress(String title, String mes) {
		showProgressDialog(title, mes);
	}

	@Override
	public void dismissProgress() {
		dismissProgressDialog();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
        EventBus.getDefault().unregister(this);
		UDPServerSocket.close();
		SimpleWebServer.stopNanoHTTPD();
		CommunicationObserver.clear();

//		if (myViewData != null) {
//			myViewData.onDestroy();
//		}
		if (naviViewData != null) {
			naviViewData.onDestroy();
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.d(TAG, "onResume()");
		super.onResume();
		if (naviViewData != null) {
			naviViewData.onResume();
		}
	}
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		Log.d(TAG, "onRestart()");
//		if (myViewData != null) {
//			myViewData.initHead();
//		}
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
		/* 从搜索界面得到的结果 */
		case RequestCode.REQUESTCODE_NAVI: {
			Bundle bundle = data.getExtras();
			ComEntity to = (ComEntity) bundle.getSerializable("poi");

			naviViewData.multCaculateForDs3(null, null, to);
			Log.d(TAG, "RequestCode.REQUESTCODE_NAVI--------------1");
		}
			break;
		case RequestCode.REQUESTCODE_UPDATA_ICON:
//			myViewData.onActivityResult();
			break;
		case RequestCode.REQUESTCODE_NAVI_DS3: {
			ComEntity from = (ComEntity) data.getSerializableExtra("from");
			ComEntity pass = (ComEntity) data.getSerializableExtra("pass");
			ComEntity to = (ComEntity) data.getSerializableExtra("to");
			naviViewData.multCaculateForDs3(from, pass, to);//lxs Navi calc route
		}
			break;
		default:
			break;
		}
	}

	@Override
	public void onBroadcast(String arg0) {
		HeartbeatEntity heartbeatEntity = new HeartbeatEntity();
		heartbeatEntity.setPhoneIP(UdpTools.getPhoneIP());
		// SharedPreTools.putString(this, Common.HUD_SN, UdpTools.getHudCode());
		heartbeatEntity.setModelNumber(UdpTools.getModelNumber());
		MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()),
				new RequestEntity(JSON.toJSONString(heartbeatEntity), InstructionSet.INSTRUCTION_AUTH_TO_HUD + ""));
		// 给HUD系统发送一次握手
		MessageManager.send(Integer.parseInt(SystemInfo.getHUD_System_Port()), new RequestEntity("",
				InstructionSet.INSTRUCTION_AUTH_TO_HUD + ""));
	}

	@Override
	public void onHeartbeat(String arg0) {
		HeartbeatEntity heartbeatEntity = new HeartbeatEntity();
		heartbeatEntity.setPhoneIP(UdpTools.getPhoneIP(this));
		if (UdpTools.getHudVersion() != null && UdpTools.getHudVersion().length() != 0) {
			SharedPreTools.putString(this, Common.HUD_VERSION, UdpTools.getHudVersion());
		}
		if (StringUtil.isStringNull(UdpTools.getHudCode())) {
			SharedPreTools.putString(this, Common.HUD_SN, UdpTools.getHudCode());
		}
		heartbeatEntity.setModelNumber(UdpTools.getModelNumber());
		MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()),
				new RequestEntity(JSON.toJSONString(heartbeatEntity),
						InstructionSet.INSTRUCTION_AUTH_HEARTBEAT_TO_PHONE + ""));

	}

	@Override
	public void onStateChange(int arg0) {

	}

	/** 手机按钮退出键，监听接口 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.e(TAG,"BACK KEY CLICK repeat count="+event.getRepeatCount());
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

			exit();
			//startActivity(new Intent(MainActivity.this,MainActivity.class));
		}
		return false;
	}

	private void exit() {
		Log.d(TAG, "exit()");
		Typeface font = Typeface.createFromAsset(getAssets(), JUtils.TypefacePath);
		ArrayList<String> titleList = new ArrayList<String>();
		titleList.add("是否退出驾驾行车");
		titleList.add("确定");
		titleList.add("取消");
		final MyAlertDialog alertDialog = new MyAlertDialog(this, titleList, new DilalogListener() {
			@Override
			public void onSure() {
				windowManager.removeViewImmediate(float_window);
				ARHudComm.getInstance().destroy();
				finish();
			}

			@Override
			public void onCancel() {
			}
		});

	}

	@Override
	public void onCarcorder(String arg0) {

	}

	@Override
	public void onContentChange(int state) {
		switch (state) {
		case 0:
			Log.i(TAG, "开始连接");
			manager.startTimer();
			break;
		case 1:
			Log.i(TAG, "连接成功");
			// 判断是否获取了版本号
			if (versionEntity == null) {
				doPost_getHUDVersion();
			}
			break;
		case 2:
			Log.i(TAG, "连接断开");
			manager.stopTimer();
			break;

		default:
			break;
		}
	}

	/**
	 * 获取HUD版本号
	 */
	private void doPost_getHUDVersion() {
		if (!StringUtil.isStringNull(UdpTools.getHudVersion())) {
			return;
		}
		paramsMap = new HashMap<String, String>();
		paramsMap.put("version", UdpTools.getHudVersion());
		HttpUtil.getInstance(this).Post(App.ZZD_REQUEST_GETHUDVERSION, paramsMap, new HttpResponseListener() {

			@Override
			public void onSuccess(RespEntity respEntity) {
				versionEntity = JSON.parseObject(respEntity.getResult(), HudVersionEntity.class);
				if (versionEntity != null) {
					SharedPreTools.putString(MainActivity.this, Common.HUD_VERSION, versionEntity.getVersion_name());
					// 将MD5保存到本地
					SharedPreTools.putString(MainActivity.this, "file_MDFive",
							Jni.Jni_encryptionStr(versionEntity.getFile_MDFive(), versionEntity.getVersion_name()));
				}

			}

			@Override
			public void onLoading(int vurrent) {

			}

			@Override
			public void onFailure(String result) {
				Log.i(TAG, result);
				dismissProgressDialog();
			}
		});
	}

}
